package com.showgood.socket;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import flash.utils.ByteArray;
import flash.utils.FlashByteArray;

public class SocketCommandEncoder extends ProtocolEncoderAdapter {
	
	private final int BUFFER_SIZE = 128;
	
	@Autowired
	@Qualifier("socketCommandFactory")
	private ISocketCommandFactory factory; 	

	@Override
	public void encode(IoSession session, Object obj, ProtocolEncoderOutput output)
			throws Exception {
		IoBuffer buf = IoBuffer.allocate(BUFFER_SIZE);
		buf.setAutoExpand(true);
		ByteArray byteArray = new FlashByteArray(buf.asOutputStream());
		
		ISocketCommand command = (ISocketCommand) obj;
		assert command != null;
		factory.pack(command, byteArray);
		
		buf.flip();
		output.write(buf);
	}

}
